from flask import flash

from app.bot.services.loggers import logger
from app.bot.services.ssh_connector import get_proxies_from_config
from app.database.enums import ServerPrivacy, ServerType
from app.database.models import Proxy
from app.server.flask_app import db
from app.server.flask_app.admin_views import MyBaseModelView


class ServerModelView(MyBaseModelView):
    def on_model_change(self, form, model, is_created):
        if is_created:
            success = 0
            errors = 0
            proxy_list = get_proxies_from_config(
                server=model,
                config_path=model.config_path,
            )
            db.session.commit()

            for proxy in proxy_list:
                try:
                    proxy = Proxy(
                        login=proxy.get("login"),
                        password=proxy.get("password"),
                        port_https=proxy.get("port"),
                        server=model,
                    )

                    if model.proxy_type == ServerType.mobile:
                        proxy.reload_type = "by_time"
                        proxy.reload_period = 5
                        if model.proxy_privacy == ServerPrivacy.private:
                            proxy.reload_link = proxy.port_https
                        else:
                            proxy.authorization_type = None

                    db.session.add(proxy)
                    db.session.commit()

                    success += 1

                except Exception as e:
                    logger.exception(e)
                    errors += 1

            flash(f"Proxies created. Successfully: {success}. With error: {errors}")
        super().on_model_change(form, model, is_created)

    column_list = (
        "id",
        "name",
        "categories",
        "ip_address",
        "country",
        "ssh_port",
        "login",
        "password",
        "status",
        "proxy_type",
        "proxy_privacy",
        "was_added",
        "provider",
    )
    column_filters = (
        "name",
        "provider",
        "categories",
        "country",
        "status",
        "was_added",
    )
    column_searchable_list = (
        "ip_address",
        "name",
        "ssh_port",
        "login",
        "password",
        "status",
    )
